#include <Python.h>
#include <stdio.h>

#include "face.h"
//wget http://127.0.0.1:8080/?action=snapshot
#define WEGET_CMD "wget http://192.168.0.105:8080/?action=snapshot -O /tmp/SearchFace.jpg"
#define SEARCHFACE_FILE "/tmp/SearchFace.jpg"

void face_initialize(void)
 {
    Py_Initialize();
    // 将当前路径添加到sys.path中
    PyObject *sys = PyImport_ImportModule("sys");
    PyObject *path = PyObject_GetAttrString(sys, "path");
    PyList_Append(path, PyUnicode_FromString("."));
 }

void face_final(void)
 {
    //释放所有引用的Python对象
    Py_Finalize();
 }

double face_category(void)
 {
    double result = 0.0;

    system(WEGET_CMD);

    if(access(SEARCHFACE_FILE,F_OK) != 0)
    {
        return result;
    }

    PyObject *pModule = PyImport_ImportModule("face");//导入face.py模块
    if (!pModule)
    {
        PyErr_Print();
        printf("Error: failed to load face.py\n");
        goto FAILED_MODULE;
    }

    PyObject *pFunc = PyObject_GetAttrString(pModule, "alibaba_face");//获取alibabacloud_face函数对象
    if (!pFunc)
    {
        PyErr_Print();
        printf("Error: failed to load alibaba_face\n");
        goto FAILED_FUNC;
    }

    PyObject *pValue = PyObject_CallObject(pFunc, NULL);//调用alibabacloud_face函数并获取返回值
    if (!pValue)
    {
        PyErr_Print();
        printf("Error: function call failed\n");
        goto FAILED_VALUE;
    }


    if  (!PyArg_Parse(pValue, "d", &result))//解析获取alibabacloud_face函数的返回值，转行为C语言格式
    {
        PyErr_Print();
        printf("Error: parse failed");
        goto FAILED_RESULT;
    }
    
    printf("result = %0.2lf\n",result);
FAILED_RESULT:
    Py_DECREF(pValue);
FAILED_VALUE:
    Py_DECREF(pFunc);
FAILED_FUNC:
    Py_DECREF(pModule);
FAILED_MODULE:

    return result;
}
